package com.hk.player.module;

import android.app.Activity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.FrameLayout;

import com.hk.player.PlayerControlView;
import com.hk.player.PlayerView;
import com.hk.player.R;
import com.hk.player.core.MonitorMediaData;
import com.zhoug.common.adapters.recycler2.BaseRecyclerViewAdapter;
import com.zhoug.common.adapters.recycler2.BaseViewHolder;
import com.zhoug.common.utils.LogUtils;

import java.lang.ref.WeakReference;
import java.util.List;

import androidx.annotation.NonNull;
import androidx.lifecycle.DefaultLifecycleObserver;
import androidx.lifecycle.Lifecycle;
import androidx.lifecycle.LifecycleOwner;
import androidx.recyclerview.widget.RecyclerView;

/**
 * @author: zhoug
 * @since: 2025-08-07
 */
public class PlayerPreviewListAdapter extends BaseRecyclerViewAdapter<MonitorMediaData> {
    private static final String TAG = ">>>PlayerListAdapter";
    private final LayoutInflater mLayoutInflater;
    private WeakReference<Activity> mActivityRef;
    private RecyclerView mRecyclerView;
    private FrameLayout mFullscreenContainer;
    private OnFullscreenChangeListener onFullscreenChangeListener;

    private VideoViewHolder mCurrentHolder;

    private FrameLayout mFullscreenVideo;
    private int mFullscreenPosition = -1;
    private boolean autoPlayFirst = false;//默认自动播放第一个
    private boolean shouldPlayFirst = false;


    public PlayerPreviewListAdapter(Activity activity, RecyclerView recyclerView, FrameLayout fullScreenContainer) {
        super(activity);
        mActivityRef = new WeakReference<>(activity);
        mRecyclerView = recyclerView;
        mFullscreenContainer = fullScreenContainer;
        mLayoutInflater = LayoutInflater.from(activity);

    }

    public void setAutoPlayFirst(boolean autoPlayFirst) {
        this.autoPlayFirst = autoPlayFirst;
    }

    public void setLifeCycle(Lifecycle lifeCycle) {
        if (lifeCycle != null) {
            lifeCycle.addObserver(new DefaultLifecycleObserver() {
                @Override
                public void onPause(@NonNull LifecycleOwner owner) {
                    if (mCurrentHolder != null) {
                        mCurrentHolder.playerView.pausePlay();
                    }
                }

                @Override
                public void onResume(@NonNull LifecycleOwner owner) {
                    if (mCurrentHolder != null) {
                        mCurrentHolder.playerView.startPlay();
                    }
                }

                @Override
                public void onDestroy(@NonNull LifecycleOwner owner) {
                    if (mCurrentHolder != null) {
                        mCurrentHolder.playerView.releasePlayer();
                    }
                }
            });
        }
    }

    public void setOnFullscreenChangeListener(OnFullscreenChangeListener onFullscreenChangeListener) {
        this.onFullscreenChangeListener = onFullscreenChangeListener;
    }

    /**
     * 列表中视频切换全屏模式监听
     */
    public interface OnFullscreenChangeListener {
        /**
         * 进入全屏模式
         */
        void onEnterFullScreen();

        /**
         * 退出全屏模式
         */
        void onExitFullscreen();
    }


    public boolean isFullScreen() {
        return mFullscreenVideo != null;
    }

    /**
     * 进入全屏模式
     *
     * @param videoContainer
     * @param position
     */
    public void enterFullScreen(FrameLayout videoContainer, int position) {
        Activity activity = mActivityRef.get();
        if (isFullScreen() || activity == null) return;
        //从RecyclerView列表中移除视频播放组件
        FrameLayout parent = (FrameLayout) videoContainer.getParent();
        parent.removeView(videoContainer);
        //添加视频播放组件到全屏容器
        mFullscreenContainer.addView(videoContainer);
        mFullscreenContainer.setVisibility(View.VISIBLE);
        mFullscreenPosition = position;
        mFullscreenVideo = videoContainer;

        if (onFullscreenChangeListener != null) {
            onFullscreenChangeListener.onEnterFullScreen();
        }
    }

    /**
     * 退出全屏模式
     */
    public void exitFullscreen() {
        Activity activity = mActivityRef.get();
        if (!isFullScreen() || activity == null) return;
        //从全屏容器中移除视频播放组件
        mFullscreenContainer.removeView(mFullscreenVideo);
        VideoViewHolder holder = getViewHolderAtPosition(mFullscreenPosition);
        if (holder != null) {
            //将播放器归还给原ViewHolder
            ((FrameLayout) holder.itemView).addView(mFullscreenVideo);
        } else {
            // 视图不可见时临时处理：添加到RecyclerView顶部（需额外处理）
            mRecyclerView.addView(mFullscreenVideo, 0);
        }

        mFullscreenVideo = null;
        if (onFullscreenChangeListener != null) {
            onFullscreenChangeListener.onExitFullscreen();
        }
    }

    public void stopPlay() {
        if (mCurrentHolder != null) {
            mCurrentHolder.playerView.stopPlay();
        }
    }

    public void pausePlay() {
        if (mCurrentHolder != null) {
            mCurrentHolder.playerView.pausePlay();
        }
    }

    public void startPlay(PlayerPreviewListAdapter.VideoViewHolder videoHolder) {
        if (videoHolder != null) {
            if (mCurrentHolder != null && mCurrentHolder != videoHolder) {
                mCurrentHolder.playerControlView.setVisibility(View.GONE);
            }
            videoHolder.playerControlView.setVisibility(View.VISIBLE);
            mCurrentHolder = videoHolder;
            videoHolder.playerView.startPlay();
        }
    }

    /**
     * 获取指定位置的ViewHolder
     *
     * @param position
     * @return
     */
    private VideoViewHolder getViewHolderAtPosition(int position) {
        RecyclerView.ViewHolder holder = mRecyclerView.findViewHolderForAdapterPosition(position);
        return (holder instanceof VideoViewHolder) ? (VideoViewHolder) holder : null;
    }

    @Override
    protected int getLayoutId(int viewType) {
        return R.layout.hk_player_preview_list_item;
    }


    @NonNull
    @Override
    public BaseViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        if (viewType == VIEW_TYPE_DATA) {
            View root = mLayoutInflater.inflate(getLayoutId(viewType), parent, false);
            return new VideoViewHolder(root, this);
        }
        return super.onCreateViewHolder(parent, viewType);
    }

    @Override
    protected void onBindData(BaseViewHolder holder, MonitorMediaData data, int position, int viewType) {
        if (data != null) {
            if (holder instanceof VideoViewHolder videoHolder) {
                LogUtils.d(TAG, "onBindData:"+position);
                PlayerView playerView = videoHolder.playerView;
                PlayerControlView playerControlView = videoHolder.playerControlView;
                playerView.setMonitorData(data);
                playerControlView.setVisibility(View.GONE);
                playerView.setOnPlayBtnClickListener((hkPlayerView, startPlay) -> {
                    if (mCurrentHolder != null && mCurrentHolder.playerView != hkPlayerView) {
                        mCurrentHolder.playerView.stopPlay();
                        mCurrentHolder.playerControlView.setVisibility(View.GONE);
                    }
                    videoHolder.playerControlView.setVisibility(View.VISIBLE);
                    mCurrentHolder = videoHolder;
                });
                playerControlView.setFullScreenBtnClickListener(v -> {
                    if (isFullScreen()) {
                        exitFullscreen();
                    } else {
                        enterFullScreen(videoHolder.videoContainer, position);
                    }
                });

                if (autoPlayFirst && shouldPlayFirst && position == 0) {
                    shouldPlayFirst = false;
                    startPlay(videoHolder);
                }else{
                    startPlay(videoHolder);
//                    videoHolder.playerView.preload();
                }
            }
        }
    }

    @Override
    public void setData(List<MonitorMediaData> data) {
        super.setData(data);
        shouldPlayFirst = true;
    }

    @Override
    public void loadSuccess(List<MonitorMediaData> data) {
        super.loadSuccess(data);
        shouldPlayFirst = true;
    }


    public static class VideoViewHolder extends BaseViewHolder {
        private final PlayerView playerView;
        private final PlayerControlView playerControlView;
        private final FrameLayout videoContainer;

        public VideoViewHolder(View itemView, BaseRecyclerViewAdapter<?> adapter) {
            super(itemView, adapter);
            videoContainer = itemView.findViewById(R.id.containerVideo);
            playerView = itemView.findViewById(R.id.playerView);
            playerControlView = itemView.findViewById(R.id.playerControlView);

        }
    }

    /**
     * 当 单个 Item 的视图 离开屏幕或被移除时触发（例如：滑动导致视图滚出屏幕、删除 Item、数据更新导致布局变化等）。
     *
     * @param holder Holder of the view being detached
     */
    @Override
    public void onViewDetachedFromWindow(@NonNull BaseViewHolder holder) {
        super.onViewDetachedFromWindow(holder);
        LogUtils.d(TAG, "onViewDetachedFromWindow:itemView 从窗口分离");
        if (holder instanceof VideoViewHolder videoViewHolder) {
            videoViewHolder.playerView.releasePlayer();
        }
    }

    /**
     * 当 整个 Adapter 与 RecyclerView 解除绑定 时触发（例如：调用 recyclerView.setAdapter(null)、Activity/Fragment 销毁、RecyclerView 被移除时）。
     *
     * @param recyclerView The RecyclerView instance which stopped observing this adapter.
     */
    @Override
    public void onDetachedFromRecyclerView(@NonNull RecyclerView recyclerView) {
        super.onDetachedFromRecyclerView(recyclerView);
    }


}
